/*
 * Copyright (c) 2015 DHC Corporation.
 */

package cn.com.dhc.danlu.yijifu;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.yiji.www.paymentcenter.YijiPayPlugin;

import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.MD5;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.hd.mall.web.webservices.entity.request.order.GetYijipayConfigRequest;
import cn.com.hd.mall.web.webservices.entity.response.order.GetYijipayConfigResponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * 易极付买家开户画面
 */
public class YJBuyerRegisterActivity extends BaseActivity {
    /**
     * 关闭activity识别码
     */
    private static final int FINISH_ACTIVITY_CODE = 1;
    /**
     * 开户页面
     */
    private WebView mWebView;
    /**
     * 开户测试地址
     */
    private String YJF_URL = "http://openapi.yijifu.net/gateway.html";
    /**
     * 开户未签名请求参数
     */
    private String[] unsignedRequestParams = new String[12];
    /**
     * 开户签名请求参数
     */
    private String[] signedRequestParams = new String[13];
    /**
     * 开户丹露Id
     */
    private String partnerId = "20160115020000649090";
    /**
     * 密钥
     */
    private String key = "36932d57fbc7cde3cbcbbb719bdc34b7";
    /**
     * 开户service
     */
    private String service = "qftDealerRegister";
    /**
     * 开户签名加密类型
     */
    private String signType = "MD5";
    /**
     * 开户加密标识
     */
    private String sign = "";
    /**
     * 注册成功后异步通知丹露后台的url
     */
    private String notifyUrl = "http://101.200.124.247:8090/yijiPay/qftDealerRegisterResNotfily.html";
    /**
     * 注册成功后回调webservices的url
     */
    private String returnUrl = "http://123.56.70.71/orders/oper/addQftUserInfo.json";
    /**
     * 注册成功重定位后的URL
     */
    private String registerSuccessUrl = "http://ewpay.yijifu.net/mapi/link/openaccountsuccess.html";
    /**
     * 开户平台
     */
    private String clientType = "MOBILE";
    /**
     * 开户http请求方式
     */
    private String protocol = "httpGet";
    /**
     * 是否需要自动生成用户名
     */
    private String autoCreate = "YES";
    /**
     * 开户未签名拼接地址
     */
    private String unsignedUrl;
    /**
     * 开户签名拼接地址
     */
    private String signedUrl;
    /**
     * 注册成功后回调webservices的url包含部分
     */
    private String returnUrlPart = "orders/oper/addQftUserInfo.json";

    private ProgressBar pb_loadding;
    private RelativeLayout rl_content;
    private LinearLayout rl_error;

    /**
     * 注册成功
     */
    private boolean registerSucessFlg = false;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == FINISH_ACTIVITY_CODE) {
                Intent intent = new Intent();
                intent.putExtra(CommonConst.BroadcastAction.BROADCAST_GET_YJF_REGISTER_ACTION, registerSucessFlg);
                setResult(RESULT_OK, intent);
                finish();
            }
        }

    };

    /**
     * 生成支付请求号(26)
     */
    public static String getPayRequestNo() {

        Calendar calendar = new GregorianCalendar();
        StringBuilder sb = new StringBuilder();
        sb.append("PR").append(calendar.get(Calendar.YEAR));
        // month
        int month = calendar.get(Calendar.MONTH);
        if (month < 10) {
            sb.append("0").append(month + 1);
        } else {
            sb.append(month + 1);
        }
        // day
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        if (day < 10) {
            sb.append("0").append(day);
        } else {
            sb.append(day);
        }
        // hour
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour < 10) {
            sb.append("0").append(hour);
        } else {
            sb.append(hour);
        }
        // minute
        int minute = calendar.get(Calendar.MINUTE);
        if (minute < 10) {
            sb.append("0").append(minute);
        } else {
            sb.append(minute);
        }
        // second
        int second = calendar.get(Calendar.SECOND);
        if (second < 10) {
            sb.append("0").append(second);
        } else {
            sb.append(second);
        }
        int millisecond = calendar.get(Calendar.MILLISECOND);
        if (millisecond < 10) {
            sb.append("00").append(millisecond);
        } else if (millisecond < 100) {
            sb.append("0").append(millisecond);
        } else {
            sb.append(millisecond);
        }

        sb.append(Math.round(Math.random() * 89999 + 10000));

        return sb.toString();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 实例化画面控件
        setContentView(R.layout.layout_yijibuyer_register);
        // 画面初始化
        init();

        getYjfConfig();
    }

    @Override
    protected String getActivityTitle() {
        return null;
    }

    /**
     * 画面初始化
     */
    private void init() {
        mWebView = (WebView) findViewById(R.id.webView);
        pb_loadding = (ProgressBar) findViewById(R.id.progressBar);
        rl_content = (RelativeLayout) findViewById(R.id.rl_content);
        rl_error = (LinearLayout) findViewById(R.id.rl_error);
        rl_error.findViewById(R.id.btn_error_retry).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                rl_error.setVisibility(View.GONE);
                mWebView.reload();
                rl_content.setVisibility(View.VISIBLE);
            }
        });
    }

    @SuppressLint({"AddJavascriptInterface", "SetJavaScriptEnabled"})
    public void showWebView(String signedUrl) {
        mWebView.loadUrl(signedUrl);
        WebSettings settings = mWebView.getSettings();
        settings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
        settings.setJavaScriptEnabled(true);

        mWebView.addJavascriptInterface(new Object() {
            @android.webkit.JavascriptInterface // 被JS调用的方法必须加此注解
            public void close() {
                finish();
            }
        }, "android");
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                view.getSettings().setJavaScriptEnabled(true);
                super.onPageFinished(view, url);
                if (url.contains(returnUrlPart)) {
                    notifyRegisterResult(true);
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed(); // 接受https
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                pb_loadding.setProgress(newProgress);
                if (newProgress == 100) {
                    // 没有title显示网址
                    pb_loadding.setVisibility(View.INVISIBLE);
                    AlphaAnimation animation = new AlphaAnimation(1.0f, 0.0f);
                    animation.setDuration(500);
                    animation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            pb_loadding.setVisibility(View.INVISIBLE);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {
                        }
                    });
                    pb_loadding.startAnimation(animation);
                } else {
                    pb_loadding.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }
        });
    }

    /**
     * 通知注册结果
     */
    private void notifyRegisterResult(boolean isSuccess) {
        // 加载进度条 隐藏webview
        registerSucessFlg = isSuccess;
        mWebView.setVisibility(View.GONE);
        mHandler.removeMessages(FINISH_ACTIVITY_CODE);
        Message message = mHandler.obtainMessage(FINISH_ACTIVITY_CODE);
        mHandler.sendMessageDelayed(message, 300);// 延迟300ms关闭activity
    }

    /**
     * 在webview中显示注册页
     */
    private void gotoRegisterPage() {
        // 未签名参数初始化
        initUnsignedParams();
        // 未签名参数数组元素按首字母排序
        unsignedRequestParams = sort(unsignedRequestParams);
        // 未签名参数拼接地址
        unsignedUrl = contactUrl(unsignedRequestParams, false);
        // 生成md5签名
        sign = createSign(unsignedUrl);
        // 签名参数初始化
        initSignedParams();
        // 签名参数拼接地址
        signedUrl = contactUrl(signedRequestParams, true);

        showWebView(signedUrl);
    }

    /**
     * 开户--未签名参数初始化
     */
    private void initUnsignedParams() {
        String partnerShopId = agent.getLoginUser().getCompanyId();
        String partnerShopName = getPreferenceUtils().getFullName();
        unsignedRequestParams[0] = "service=" + service;
        unsignedRequestParams[1] = "partnerId=" + partnerId;
        unsignedRequestParams[2] = "orderNo=" + getPayRequestNo();
        unsignedRequestParams[3] = "signType=" + signType;
        unsignedRequestParams[4] = "notifyUrl=" + notifyUrl;
        unsignedRequestParams[5] = "partnerShopName=" + partnerShopName;
        unsignedRequestParams[6] = "partnerShopId=" + partnerShopId;
        unsignedRequestParams[7] = "clientType=" + clientType;
        unsignedRequestParams[8] = "protocol=" + protocol;
        unsignedRequestParams[9] = "returnUrl=" + returnUrl;
        unsignedRequestParams[10] = "autoCreate=" + autoCreate;
        unsignedRequestParams[11] = "version=2.0";
    }

    /**
     * 开户--签名参数初始化
     */
    private void initSignedParams() {
        System.arraycopy(unsignedRequestParams, 0, signedRequestParams, 0, unsignedRequestParams.length);
        signedRequestParams[12] = "sign=" + sign;
        signedRequestParams = sort(signedRequestParams);
    }

    /**
     * 开户--未签名参数数组元素按首字母排序
     */
    private String[] sort(String[] params) {
        // 调用数组的静态排序方法sort,且不区分大小写
        Arrays.sort(params, String.CASE_INSENSITIVE_ORDER);
        return params;
    }

    /**
     * 开户-- 拼接地址
     */
    private String contactUrl(String[] params, Boolean isSigned) {
        String contactParams = "";
        String url;
        for (int i = 0; i < params.length; i++) {
            if (i == 0) {
                contactParams += params[i];
            } else {
                contactParams += "&" + params[i];
            }
        }
        if (!isSigned) { // 未签名参数拼接地址(后面加上密钥)
            // url = contactParams;
            url = contactParams + key;
        } else { // 签名参数拼接地址(前面加上测试地址)
            url = YJF_URL + "?" + contactParams;
        }
        return url;
    }

    /**
     * 开户-- 生成md5签名
     */
    private String createSign(String unsignedUrl) {
        return MD5.getMD5Str(unsignedUrl);
    }

    /**
     * 获取易极付常量
     */
    private void getYjfConfig() {
        GetYijipayConfigRequest getYijipayConfigRequest = new GetYijipayConfigRequest();
        getYijipayConfigRequest.setToken(agent.getToken());
        // 调用易极付常量接口
        agent.getApi().getYifConfigConstants(getYijipayConfigRequest).compose(OperatorUtils.<GetYijipayConfigResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<GetYijipayConfigResponse>(YJBuyerRegisterActivity.this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess(GetYijipayConfigResponse getYijipayConfigResponse) {
                        // 常量赋值
                        YJF_URL = getYijipayConfigResponse.getYjfUrl();
                        partnerId = getYijipayConfigResponse.getPartnerId();
                        key = getYijipayConfigResponse.getKey();
                        notifyUrl = getYijipayConfigResponse.getNotifyUrl();
                        protocol = getYijipayConfigResponse.getProtocol();
                        registerSuccessUrl = getYijipayConfigResponse.getRegisterSuccessUrl();
                        returnUrl = getYijipayConfigResponse.getReturnUrl();
                        service = getYijipayConfigResponse.getService();
                        autoCreate = getYijipayConfigResponse.getAutoCreate();
                        if (!TextUtils.isEmpty(partnerId) && !TextUtils.isEmpty(key)) {
                            YijiPayPlugin.setPartnerId(partnerId);
                            YijiPayPlugin.setSecretKey(key);
                            // 开户
                            gotoRegisterPage();
                        }
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        // 注册流程失败
                        ToastUtil.getInstance().show(R.string.yjf_buyer_register_fail);
                        notifyRegisterResult(false);
                    }
                });
    }
}